using Extensions;
using Gameplay.PVE.Entity;
using Gameplay.PVE.Utils;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using Yoozoo.Framework.Managers;
using Yoozoo.Libs;
using Yoozoo.UI.YGUI;

namespace Gameplay.PVE
{
    public class HudComponent : IComponent,ITransmit
    {
        //ui
        protected UnitBase unit;
        protected GameObject uiObject;
        protected Transform bloodBarTrans;
        protected Text bloodText;
        protected Transform cameraTrans;

        private GameObject iconEnemy;
        private GameObject iconQuestion;
        private GameObject iconAlert;
        private GameObject iconBoss;
        private GameObject iconElite;
        
        
        protected GameObject bloodBar;

        private int enemyUIState = 0;//0 红色标记 1 问号 2 感叹号
        private float stateStartTime = 0;

        private Image bloodBarImageTemp;
        private Image bloodBarImage;
        private Transform bloodBarTempTrans;
        private float startDiffTime;//开始发现百分比不同的时间
        private float closeDelay = 0.2f;//靠近的延迟时间
        private float tempPercent;//过度血条的百分比
        protected float realPercent;//血条实际的百分比

        private Image mpBarImage;

        private Image shieldBarImage;
        private GameObject shieldBar;

        private GameObject reload;
        private Image reloadProgress;
        private GameObject hiding;

        private float startReloadTime;
        private bool isBloodReduced = true;

        private bool isGlobalHide = false;
        private bool hudActiveStatus;
        
        private int uiResId;
        
        void IClass.OnReset()
        {
            isGlobalHide = false;
            enemyUIState = 0;
            stateStartTime = 0;
            if (uiObject != null)
            {
                PveResourceManager.RecoverResource(uiObject,PveResourceManager.EPveResType.Hud,uiResId);
                uiObject = null;
            }
            isBloodReduced = true;
            bloodText = null;
            mpBarImage = null;
        }

        void IComponent.OnInitialize(UnitBase unit)
        {
            Initialize(unit);
        }
        
        public void Dispose()
        {
            ((IClass)this).OnReset();
        }

        public void Birth()
        {
            ((IComponent)this).OnBirth();
        }
        
        void IComponent.OnUpdate()
        {
           Update();
        }

        public void OnFixedUpdate()
        {
            if (uiObject == null)
            {
                return;
            }
            if (unit.Data.hudPoint != null)
            {
                uiObject.transform.position = unit.Data.hudPoint.position+ new Vector3(0,unit.Data.hudHeight,0);
            }
            uiObject.transform.forward = cameraTrans.forward;
        }
        
        protected void UpdateHpTransition()
        {
            if (!isBloodReduced)
            {
                //如果是因为长度调整造成的血量减少，则不进行变化
                float percent =  (float) unit.Data.CurrentHp / unit.Data.TotalHp;
                float shieldPercent = (float) unit.Data.CurrentShield / unit.Data.TotalShield;
                if (percent + shieldPercent == 0)
                {
                    tempPercent = 0;
                }
                else
                {
                    tempPercent = shieldPercent / (shieldPercent + percent);
                }
                //bloodBarTempTrans.localScale = new Vector3(tempPercent, 1, 1);
                bloodBarImageTemp.fillAmount = tempPercent;
                return;
            }

            if (startDiffTime == 0)
            {
                if (realPercent < tempPercent)
                {
                    startDiffTime = TimeManager.logicTime;
                }
                else if (realPercent > tempPercent)
                {
                    tempPercent = realPercent;
                }
            }
            else if (TimeManager.logicTime - startDiffTime > closeDelay)
            {
                float diff = 1 * TimeManager.LogicDeltaTime;
                if (tempPercent - realPercent > diff)
                {
                    tempPercent -= diff;
                }
                else
                {
                    tempPercent = realPercent;
                    startDiffTime = 0;
                }
                //bloodBarTempTrans.localScale = new Vector3(tempPercent,1,1);
                //bloodBarImageTemp.fillAmount = tempPercent;
                //bloodBarTempTrans.localScale = new Vector3(tempPercent, 1, 1);
                bloodBarImageTemp.fillAmount = tempPercent;
            }

        }

        public virtual void Update()
        {
            if (unit.Data.isDead)
            {
                return;
            }

             UpdateHpTransition();
            
            if (startReloadTime != 0)
            {
                float percent = (TimeManager.logicTime - startReloadTime) / unit.Data.reloadTime;
                if (percent >= 1)
                {
                    startReloadTime = 0;
                }
                else
                {
                    reloadProgress.fillAmount = percent;
                }
            }


            if (unit.Data.team == 2)
            {
                if (enemyUIState == 1)
                {
                    if (TimeManager.logicTime - stateStartTime > 0.5f)
                    {
                        enemyUIState = 2;
                        stateStartTime = TimeManager.logicTime;
                        RefreshEnemyUI();
                    }
                }
                else if (enemyUIState == 2)
                {
                    if (TimeManager.logicTime - stateStartTime > 1f)
                    {
                        enemyUIState = 0;
                        RefreshEnemyUI();
                    }
                }
            }
        }

        public virtual void Initialize(UnitBase unit)
        {
            cameraTrans = PveCameraManager.Instance.mainCamera.transform;
            this.unit = unit;
            uiResId = 11;
            if (unit.Data.team == 0)
            {
                uiResId = 11;
            }
            else if (unit.Data.isBoss)
            {
                uiResId = 15;
            }
            else if (unit.Data.isElite)
            {
                uiResId = 14;
            }
            else if (unit.Data.team == 2)
            {
                uiResId = 13;
            }
            uiObject = PveResourceManager.GetResource(PveResourceManager.EPveResType.Hud, uiResId);
            
            /*if (unit.Data.team == 0)//我方
            {
                if (unit.Data.id == 0)//主角
                {
                    uiObject = PveResourceManager.GetResource(PveResourceManager.EPveResType.Hud, 11);
                }
                else//友军
                {
                    //todo
                    if (unit.Data.isSummonUnit)
                    {
                        uiObject = PveResourceManager.GetResource(PveResourceManager.EPveResType.Hud, 14);
                    }
                    else
                    {
                        uiObject = PveResourceManager.GetResource(PveResourceManager.EPveResType.Hud, 12);
                    }
                }
            }
            else
            {
                if (unit.Data.isBoss)
                {
                    //todo
                    uiObject = PveResourceManager.GetResource(PveResourceManager.EPveResType.Hud, 15);
                }
                else if (unit.Data.isElite)
                {
                    //todo
                    uiObject = PveResourceManager.GetResource(PveResourceManager.EPveResType.Hud, 14);
                }
                else
                {
                    //todo
                    uiObject = PveResourceManager.GetResource(PveResourceManager.EPveResType.Hud, 13);
                }
            }*/

            if (uiObject == null)//临时处理
            {
                uiObject = PveResourceManager.GetResource(PveResourceManager.EPveResType.Hud, 11);
                uiResId = 11;
            }

            uiObject.transform.SetParent(unit.gameObject.transform);
            float modelScale = 1;
            uiObject.SetActive(true);
            float scale = 0.012f;
            uiObject.transform.localScale = scale * PveUtils.globalRatio * Vector3.one;

            var canvas = uiObject.GetComponent<Canvas>();
            canvas.enabled = true;
            var canvasGroup = uiObject.GetComponent<CanvasGroup>();
            canvasGroup.enabled = true;
            
            bloodBar = uiObject.transform.Find("bloodBar").gameObject;
            SetBloodBarVisible(unit.Data.team == 0  || unit.Data.isBoss || unit.Data.isElite);
            bloodBarTrans = uiObject.transform.Find("bloodBar/barHpBg/barHp");
            bloodBarImage = bloodBarTrans.gameObject.GetComponent<Image>();
            bloodBarImage.fillAmount = 1;
            bloodBarTempTrans = uiObject.transform.Find("bloodBar/barHpBg/barHpTemp");
            mpBarImage = null;
            var mpBg = uiObject.transform.Find("bloodBar/barMpBg");
            if (mpBg != null)
            {
                if (unit.Data.HasSkillInitiative())
                {
                    mpBg.gameObject.SetActive(true);
                    var mpTrans = mpBg.Find("barMp");
                    if (mpTrans != null)
                    {
                        mpBarImage = mpTrans.GetComponent<Image>();
                        mpBarImage.fillAmount = 0;
                    }
                }
                else
                {
                    mpBg.gameObject.SetActive(false);
                }
            }
            
            bloodBarImageTemp = bloodBarTempTrans.gameObject.GetComponent<Image>();
            bloodBarImageTemp.fillAmount = 1;
            
            shieldBar = bloodBar.transform.Find("barHpBg").Find("barShieldBg").gameObject;
            shieldBarImage = shieldBar.transform.Find("barShield").gameObject.GetComponent<Image>();
            shieldBar.SetActive(true); //背景是透明图片，需要一直保持true
            
            tempPercent = 1;
            realPercent = 1;
            if (unit.Data.isBoss || unit.Data.isElite)
            {
                var name = bloodBar.transform.Find("name");
                if (name != null)
                {
                    var text = name.GetComponent<TextMeshProUGUI>();
                    text.text = PveUtils.GetLangText(unit.Data.monsterConfig.monster_name);
                    var quality = unit.Data.monsterConfig.monster_name_quality;
                    string color = "";
                    if (quality == 1)
                    {
                        color = "#becace";
                    }
                    else if (quality == 2)
                    {
                        color = "#6fff85";
                    }
                    else if (quality == 3)
                    {
                        color = "#6ca4ff";
                    }
                    else if (quality == 4)
                    {
                        color = "#f68eff";
                    }
                    else
                    {
                        color = "#ffca54";
                    }

                    Color realColor;
                    ColorUtility.TryParseHtmlString(color, out realColor);
                    text.overrideColorTags = true;
                    text.color = realColor.gamma;
                }
            }
        }


        private void RefreshEnemyUI()
        {
            return;
            iconEnemy.SetActive(unit.Data.team == 2 && enemyUIState == 0);
            iconQuestion.SetActive(unit.Data.team == 2 && enemyUIState == 1);
            iconAlert.SetActive(unit.Data.team == 2 && enemyUIState == 2);
        }

        void IComponent.OnBirth()
        {
            InitPosition();
            if (PveManager.Instance.isInRpg)
            {
                (this as ITransmit).OnTransmit(ETransmitType.ToRPG,null);
            }
        }

        void IComponent.OnDead()
        {
            SetBloodBarVisible(false);
        }

        protected virtual void InitPosition()
        {
            if (unit.Data.hudPoint != null)
            {
                uiObject.transform.localPosition = unit.Data.hudPoint.localPosition;
            }
            else
            {
                uiObject.transform.localPosition = new Vector3(0,PveGlobalVlues.HudHeight, 0);
            }
        }

        public void HideOrShowBloodBar()
        {
            if ((float) unit.Data.CurrentHp / unit.Data.TotalHp - 1 >= -0.01f)
            {
                SetBloodBarVisible(false);
                return;
            }
            if (bloodBar.activeSelf)
            {
                SetBloodBarVisible(false);
            }
            else
            {
                SetBloodBarVisible(true);
            }
        }
        private void SetBloodBarVisible(bool visible)
        {
            hudActiveStatus = PveFlyTextManager.Instance.showBloodBar && visible;
            bloodBar.SetActive(hudActiveStatus && !isGlobalHide);
        }

        protected void UpdateMp()
        {
            if (unit.Data.TotalMp == 0 || !PveManager.Instance.isInRpg || mpBarImage == null)
            {
                return;
            }
            mpBarImage.fillAmount = unit.Data.CurrentMp / unit.Data.TotalMp;
        }
        
        protected virtual void UpdateHp()
        {
            if (unit.Data.TotalHp == 0 || !PveManager.Instance.isInRpg)
            {
                return;
            }
            
            //获取血条
            float percent = (float) unit.Data.CurrentHp / unit.Data.TotalHp;
            if (percent < 1 || unit.Data.isBoss || unit.Data.isElite)
            {
                SetBloodBarVisible(true);
            }
            if (percent < 0)
            {
                percent = 0;
            }
            //获取护盾条
            float shieldPercent = (float) unit.Data.CurrentShield / unit.Data.TotalShield;
            if (shieldPercent > 0.3f) //护盾条的最大长度不超过 0.3
            {
                shieldPercent = 0.3f;
            }
            if (shieldPercent + percent > 1)
            {
                //如果血条和护盾条相加超出范围，则调整
                float total = shieldPercent + percent;
                shieldPercent /= total;
                percent /= total;
                isBloodReduced = false; //防止tempBloodbar进行变化
            }
            else
            {
                isBloodReduced = true;
            }
            
            realPercent = percent;
            bloodBarImage.fillAmount = percent;
            shieldBarImage.fillAmount = percent + shieldPercent;
            
        }
        
        public void SetLayer(int layer)
        {
            if (uiObject)
            {
                uiObject.SetLayerRecursively(layer);
            }
        }
        
        void ITransmit.OnTransmit(ETransmitType type, BaseTransmitArg arg)
        {
            if (unit.Data.isDead)
            {
                return;
            }
            if (type == ETransmitType.UpdateHp)
            {
                //Debug.LogError(unit.Data.id + " " + unit.Data.CurrentHp);
                UpdateHp();
            }
            else if (type == ETransmitType.UpdateMp)
            {
                UpdateMp();
            }
            else if (type == ETransmitType.SearchSuccess)
            {
                if (unit.Data.team == 2 && !unit.Data.IsInAttack() && !PveManager.Instance.isInRpg)
                {
                    enemyUIState = 1;
                    RefreshEnemyUI();
                    stateStartTime = TimeManager.logicTime;
                }
            }
            else if (type == ETransmitType.ToRPG)
            {
                uiObject.transform.forward = cameraTrans.forward;
                enemyUIState = 3;
                RefreshEnemyUI();
                /*if (unit.Data.isManualMoving)
                {
                    bloodBar.SetActive(true);
                }*/
                UpdateHp();
                if (unit.Data.isSummonUnit)
                {
                    SetBloodBarVisible(false);
                }
            }
            else if (type == ETransmitType.RPGStart)
            {
                if (unit.Data.team == 0)//unit.Data.isManualMoving)
                {
                    UpdateHp();
                    SetBloodBarVisible(true);
                }
                else
                {
                    SetBloodBarVisible(unit.Data.isBoss || unit.Data.isElite);
                }
            }
            else if (type == ETransmitType.StageStart)
            {
                //enemyUIState = 3;
                //RefreshEnemyUI();
                SetBloodBarVisible(false);
            }
            else if (type == ETransmitType.HideIn)
            {
                //hiding.SetActive(true);
            }
            else if (type == ETransmitType.HideOut)
            {
                //hiding.SetActive(false);
            }
            else if (type == ETransmitType.ReloadStart)
            {
                if (PveManager.Instance.isInRpg && false)
                {
                    reload.SetActive(true);
                    startReloadTime = TimeManager.logicTime;
                }
            }
            else if (type == ETransmitType.ReloadEnd)
            {
                if (PveManager.Instance.isInRpg && false)
                {
                    reload.SetActive(false);
                }
            }
            else if (type == ETransmitType.ShowHud)
            {
                isGlobalHide = false;
                SetBloodBarVisible(hudActiveStatus);
                //SetBloodBarVisible(true);
            }
            else if (type == ETransmitType.HideHud)
            {
                isGlobalHide = true;
                SetBloodBarVisible(hudActiveStatus);
                //SetBloodBarVisible(false);
            }
        }
    }
}